package com.jinyu.jyly.ui.mine.recharge;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.jinyu.jyly.R;
import com.jinyu.jyly.base.BaseLazyFragment;
import com.jinyu.jyly.bean.AllInfoBean;
import com.jinyu.jyly.global.GlobalConstants;
import com.jinyu.jyly.net.http.HttpUrl;
import com.jinyu.jyly.utils.AES;
import com.jinyu.jyly.utils.SharedPreferencesUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * 银行卡收款码
 *
 * @author 62485
 */
public class RechargeMoneyBankTabFragment extends BaseLazyFragment<RechargeMoneyPresenter> implements RechargeMoneyContract.View {

    @BindView(R.id.btn_sub)
    Button btnSub;
    @BindView(R.id.iv_upload)
    ImageView iv_upload;
    @BindView(R.id.et_money_num)
    EditText et_money_num;

    @BindView(R.id.tv_bank_name)
    TextView tv_bank_name;
     @BindView(R.id.et_account_name)
    TextView et_account_name;
     @BindView(R.id.et_account_num)
    TextView et_account_num;


    private RechargeMoneyPresenter mPresenter;
    private int themeId;
    private String type;
    private UploadManager uploadManager;
    private String qiniuToken;
    private String qiNiuImg = "";


    public static RechargeMoneyBankTabFragment newInstance(String type) {
        RechargeMoneyBankTabFragment newFragment = new RechargeMoneyBankTabFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    @Override
    protected View initView(ViewGroup container) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_recharge_money_bank_tab, container, false);
        return view;
    }

    @Override
    protected void loadData() {
        initIntent();
        qiniuToken = (String) SharedPreferencesUtils.getParam(getActivity(), GlobalConstants.QINIU_TOKEN, "");
        themeId = R.style.picture_default_style;
        setPermissions();
        initQiNiu();
        initData();
    }

    private void initIntent() {
        Bundle bundle = getArguments();
        if(bundle != null){
            type = bundle.getString("type");
        }
    }

    private void initData() {
        mTipDialog.show();
        mPresenter.getChonePayment();
    }

    /**
     * 初始化七牛云
     */
    private void initQiNiu() {
        Configuration config = new Configuration.Builder()
                .connectTimeout(90)              // 链接超时。默认90秒
                .useHttps(true)                  // 是否使用https上传域名
                .useConcurrentResumeUpload(true) // 使用并发上传，使用并发上传时，除最后一块大小不定外，其余每个块大小固定为4M，
                .concurrentTaskCount(3)          // 并发上传线程数量为3
                .responseTimeout(90)             // 服务器响应超时。默认90秒
                .recorder(null)              // recorder分片上传时，已上传片记录器。默认null
//                .recorder(recorder, keyGen)      // keyGen 分片上传时，生成标识符，用于片记录器区分是那个文件的上传记录
//                .zone(FixedZone.zone0)           // 设置区域，不指定会自动选择。指定不同区域的上传域名、备用域名、备用IP。
                .build();
// 重用uploadManager。一般地，只需要创建一个uploadManager对象
        uploadManager = new UploadManager(config);
    }


    @Override
    public RechargeMoneyPresenter getPresenter() {
        if (mPresenter == null) {
            mPresenter = new RechargeMoneyPresenter(getActivity(), this);
        }
        return mPresenter;
    }

    @Override
    public void onFailer(Throwable throwable) {
        mTipDialog.dismiss();
    }

    /**
     * 设置相关权限
     */
    private void setPermissions() {
        // 清空图片缓存，包括裁剪、压缩后的图片 注意:必须要在上传完成后调用 必须要获取权限
        RxPermissions permissions = new RxPermissions(getActivity());
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    PictureFileUtils.deleteCacheDirFile(getActivity());
                } else {
                    Toast.makeText(getActivity(),
                            getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }


    private int imgId = -1;

    @Override
    public void onUpdataImg(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()) {
            case 200:
                String beanData = infoBean.getData();
                String result = null;
                try {
                    result = AES.decrypt(beanData);
                    JSONObject rootObject = new JSONObject(result);
                    imgId = rootObject.optInt("id");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 充值
     *
     * @param infoBean
     */
    @Override
    public void onAddChong(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()) {
            case 200:
                String data = infoBean.getData();
                showToast("充值成功");
                getActivity().finish();
                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:
                break;
        }
    }

    /**
     * 获取充值二维码
     * @param infoBean
     */
    @Override
    public void getChonePayment(AllInfoBean infoBean) {
        mTipDialog.dismiss();
        switch (infoBean.getStatus()){
            case 200:
                try {
                    String infodata = AES.decrypt(infoBean.getData());
                    JSONObject jsonObject = new JSONObject(infodata);
                    String bank = jsonObject.optString("bank");
                    String bank_num = jsonObject.optString("bank_num");
                    String bank_name = jsonObject.optString("bank_name");
                    String bank_little_name = jsonObject.optString("bank_little_name");
                    tv_bank_name.setText(bank);
                    et_account_name.setText(bank_name);
                    et_account_num.setText(bank_num);

                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case 422:
                showToast(infoBean.getMsg());
                break;
            default:break;
        }
    }

    private final int REQUEST_HEADER = 1111;

    @OnClick({R.id.btn_sub, R.id.iv_upload})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_sub:
                //提交充值
                String money_num = et_money_num.getText().toString().trim();
                if (TextUtils.isEmpty(money_num)) {
                    showToast("金额不能为空");
                    return;
                }

//                if (imgId == -1) {
//                    showToast("请选择图片");
//                    return;
//                }

                if (TextUtils.isEmpty(qiNiuImg)) {
                    showToast("请上传凭证");
                    return;
                }

                if ("0".equals(qiNiuImg)) {
                    showToast("上传凭证失败，请重新上传");
                    return;
                }


                boolean showing = mTipDialog.isShowing();
                if(!showing){
                    try {
                        //修改
                        mTipDialog.show();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("money", Float.valueOf(money_num)); //37
                        jsonObject.put("image", 0); //37
                        jsonObject.put("qiniu", qiNiuImg);
                        String param = AES.encryptToHexString(jsonObject.toString());
                        mPresenter.addChong(param);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.iv_upload:
                //上传图片
                setPicutureImage(1, PictureConfig.SINGLE, null, REQUEST_HEADER);
                break;
        }
    }

    /**
     * 打开选择器
     */
    private void setPicutureImage(int maxNum, int mode, List<LocalMedia> selectList, int requestcode) {
        PictureSelector.create(RechargeMoneyBankTabFragment.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(maxNum)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(mode)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .previewVideo(true)// 是否可预览视频
                .enablePreviewAudio(true) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(false)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .openClickSound(false)// 是否开启点击声音
                .selectionMedia(selectList)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(requestcode);//结果回调onActivityResult code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_HEADER:
                    //头像
                    String img_Url = getRequestCodeData(data);

                    File tempFile = new File(img_Url);
                    String fileName = tempFile.getName();
                    //头像
//                    List<MultipartBody.Part> parts = new ArrayList<>();
//                    parts.add(toRequestBodyOfImage(tempFile, fileName));
//                    mPresenter.updataImg(parts);

                    mTipDialog.show();
                    //直接上传到七牛云
                    //设置上传后文件的key
                    uploadManager.put(img_Url, fileName, qiniuToken, new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo rinfo, JSONObject response) {
                            //显示上传后文件的url
                            mTipDialog.dismiss();
                            if (rinfo.isOK()) {
                                qiNiuImg = key;
                                mTipDialog.show();
                                RequestOptions options = new RequestOptions()
                                        .centerCrop()
                                        .placeholder(R.drawable.image_loding) //占位符 也就是加载中的图片
                                        .error(R.mipmap.image_error)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL);
                                Glide.with(getActivity())
                                        .load(HttpUrl.QIUNIU_PATH +key)
                                        .apply(options)
                                        .addListener(new RequestListener<Drawable>() {
                                            @Override
                                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                                mTipDialog.dismiss();
                                                showToast("网络异常，上传失败，请稍后重试");
                                                Log.e("shibai",e.toString());
                                                return false;
                                            }

                                            @Override
                                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                                mTipDialog.dismiss();
                                                showToast("上传成功");
                                                return false;
                                            }
                                        })
                                        .into(iv_upload);
                                Log.i("qiniu", "Upload Success");
                            } else {
                                qiNiuImg = "0";
                                Log.i("qiniu", "Upload Fail");
                                //如果失败，这里可以把 info 信息上报自己的服务器，便于后面分析上传错误原因
                            }
                        }
                    }, new UploadOptions(null, "image/png", true, null, null));



                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 获取相关data数据
     *
     * @param data
     */
    private String getRequestCodeData(Intent data) {
        String path = "";
        if (data == null) {
            showToast("图片选择失败");
            return "";
        }
        List<LocalMedia> licenseList = PictureSelector.obtainMultipleResult(data);
        if (licenseList != null && licenseList.size() != 0) {
            LocalMedia localMedia = licenseList.get(0);
            if (localMedia.isCut() && !localMedia.isCompressed()) {
                // 裁剪过
                path = localMedia.getCutPath();
            } else if (localMedia.isCompressed() || (localMedia.isCut() && localMedia.isCompressed())) {
                // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                path = localMedia.getCompressPath();
            } else {
                // 原图
                path = localMedia.getPath();
            }
            Log.e("选择了图片", path);
        }
        return path;
    }


    private MultipartBody.Part toRequestBodyOfImage(File tempFile, String name) {
        RequestBody fileRQ = RequestBody.create(MediaType.parse("image/jpg"), tempFile);
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", name, fileRQ);
        return part;
    }


}
